package cn.bingoo.nginx;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.lang.StringUtils;

public class HttpConnectionUtils {

    public static final String CHARSET = "UTF-8";

    /**
     * 获取Connection。
     * @return Connection。
     * @throws MalformedURLException
     * @throws IOException
     */
    public static HttpURLConnection getConnection(String serverUrl) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(serverUrl).openConnection();
        String cntType = "application/x-www-form-urlencoded;charset=" + CHARSET;
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");
        conn.setRequestProperty("User-Agent", "ResMgr-sdk-java");
        conn.setRequestProperty("Content-Type", cntType);
        return conn;
    }

    /**
     * 获取Connection。
     * @return Connection。
     * @throws MalformedURLException
     * @throws IOException
     */
    public static void disconnect(HttpURLConnection conn) {
        if (conn != null) {
            conn.disconnect();
        }
    }

    /**
     * 获取响应内容。
     * @param conn 连接。
     * @return 响应内容的字符串。
     * @throws IOException
     */
    public static String getRspAsString(HttpURLConnection conn) throws IOException {
        String charset = getResponseCharset(conn.getContentType());
        InputStream es = conn.getErrorStream();
        if (es == null) {
            return getStreamAsString(conn.getInputStream(), charset);
        }
        String msg = getStreamAsString(es, charset);
        if (StringUtils.isEmpty(msg)) {
            throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
        }
        throw new IOException(msg);
    }

    /**
     * 响应的字符编码。
     * @param ctype
     * @return
     */
    private static String getResponseCharset(String ctype) {
        String charset = "UTF-8";
        if (!StringUtils.isEmpty(ctype)) {
            String[] params = ctype.split(";");
            for (String param : params) {
                param = param.trim();
                if (param.startsWith("charset")) {
                    String[] pair = param.split("=", 2);
                    if (pair.length == 2) {
                        if (!StringUtils.isEmpty(pair[1])) {
                            charset = pair[1].trim();
                        }
                    }
                    break;
                }
            }
        }
        return charset;
    }

    /**
     * 读取响应流。
     * @param stream
     * @param charset
     * @return
     * @throws IOException
     */
    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
            StringWriter writer = new StringWriter();
            char[] chars = new char[256];
            int count = 0;
            while ((count = reader.read(chars)) > 0) {
                writer.write(chars, 0, count);
            }
            return writer.toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }
}
